const path = require("path");
const resolve = (dir) => path.join(__dirname, dir);
const IS_PROD = ["production", "prod"].includes(process.env.NODE_ENV);
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

/**多页面配置 */
const glob = require("glob");
const pagesInfo = require("./pages.config");
const pages = {};

glob.sync("./src/pages/**/main.js").forEach((entry) => {
  let chunk = entry.match(/\.\/src\/pages\/(.*)\/main\.js/)[1];
  const curr = pagesInfo[chunk];
  if (curr) {
    pages[chunk] = {
      entry,
      ...curr,
      chunk: ["chunk-vendors", "chunk-common", chunk],
    };
  }
});

module.exports = {
  publicPath: IS_PROD ? "/iap/login" : "", // 默认'/'，部署应用包时的基本 URL
  outputDir: "../webapp/login", // 'dist', 生产环境构建文件的目录
  // assetsDir: "", // 相对于outputDir的静态资源(js、css、img、fonts)目录
  lintOnSave: false,
  runtimeCompiler: true, // 是否使用包含运行时编译器的 Vue 构建版本
  productionSourceMap: !IS_PROD, // 生产环境的 source map
  parallel: require("os").cpus().length > 1, //使用多线程否---多余
  pwa: {},
  pages,
  css: {
    loaderOptions: {
      stylus: {
        preferPathResolver: "webpack",
        paths: [path.join(__dirname, "src/stylus")],
        import: ["global.styl"],
      },
    },
  },
  chainWebpack: (config) => {
    // 修复HMR
    config.resolve.symlinks(true);

    // 使用svg组件
    config.module
      .rule("svg")
      .exclude.add(resolve("src/assets/svg"))
      .end();

    config.module
      .rule("icons")
      .test(/\.svg$/)
      .include.add(resolve("src/assets/svg"))
      .end()
      .use("svg-sprite-loader")
      .loader("svg-sprite-loader")
      .options({
        symbolId: "icon-[name]",
      });

    // 添加别名
    config.resolve.alias
      .set("@", resolve("src"))
      .set("@assets", resolve("src/assets"))
      .set("@components", resolve("src/components"))
      .set("@views", resolve("src/views"))
      .set("@router", resolve("src/router"))
      .set("@datas", resolve("src/datas"))
      .set("@libs", resolve("src/libs"))
      .set("@api", resolve("src/api"))
      .set("@pages", resolve("src/pages"))
      .set("@store", resolve("src/store"));

    return config;
  },
  configureWebpack: (config) => {
    const plugins = [
      new CleanWebpackPlugin({
        cleanOnceBeforeBuildPatterns: ["**/*", "!WEB-INF", "!WEB-INF/*"],
      }),
    ];
    config.plugins = [...config.plugins, ...plugins];
  },
  devServer: {
    open: false, // 浏览器访问地址: http://172.20.6.250:8081/pc.html#/
    proxy: {
      "/iap": {
        // target: 'http://172.20.6.228:80', // 目标代理接口地址 wec-iap-auth
        target: "http://iwecloud16:31421", // 目标代理接口地址
        secure: false,
        changeOrigin: true, // 开启代理，在本地创建一个虚拟服务端
      },
    },
  },
};
